
#include "DYSvrNetMan.h"
#include "stdio.h"


int DYSvrNetMan::TcpViewerDispatch(SOCKET hClientSocket,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	char szRetBuffer[256];
	memset(szRetBuffer,0,sizeof(szRetBuffer));

	NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)szRetBuffer;
	pRetMsgHead->nMsgType = pMsgHead->nMsgType + 1;

// 	SOCKADDR_IN addrPeer;
// 	int nAddrLen = sizeof(addrPeer);
// 	getpeername(hClientSocket, (PSOCKADDR) &addrPeer, &nAddrLen);
// 
// 	char szPeerIP[128] = { 0 };
// 	sprintf(szPeerIP, "%s", inet_ntoa(addrPeer.sin_addr));


	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_REALSTREAM:
		{
			TG_CONNECT_INFO *pInfo = (TG_CONNECT_INFO*)pBuffer;

            nRet = m_xSessionMan.CreateConnection(pRetMsgHead,pInfo,hClientSocket);
 		}
		break;
	default:
		{
			nRet = TG_ERR_FAILURE;
		}
		break;
	}


	if( TG_ERR_SUCCESS != nRet )
	{
		pRetMsgHead->nFrameSize = 0;
		pRetMsgHead->nErrFlag   = nRet;

		send(hClientSocket,(char*)szRetBuffer,sizeof(NET_PACKET_HEAD),0);

		close( hClientSocket );
		hClientSocket = NULL;
	}

	return nRet;
}

int DYSvrNetMan::UdpViewerDispatch(SOCKET hSocket,TG_UDP_ADDR *pAddr,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	char szRetBuffer[256];
	memset(szRetBuffer,0,sizeof(szRetBuffer));

	NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)szRetBuffer;
	pRetMsgHead->nMsgType = pMsgHead->nMsgType + 1;

// 	char szPeerIP[128] = { 0 };
// 	sprintf(szPeerIP, "%s", inet_ntoa(pAddr->xAddr.sin_addr));


	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_REALSTREAM:
		{
			TG_CONNECT_INFO *pInfo = (TG_CONNECT_INFO*)pBuffer;
			

			nRet = m_xSessionMan.CreateConnection(pRetMsgHead,pInfo,hSocket,pAddr);
 		}
		break;
	default:
		{
			nRet = UdpViewerCommand(hSocket,pAddr,pMsgHead,pBuffer);
		}
		break;
	}

	if( TG_ERR_SUCCESS != nRet )
	{
		pRetMsgHead->nFrameSize = 0;
		pRetMsgHead->nErrFlag   = nRet;

		sendto( hSocket,
			(char*)szRetBuffer,sizeof(NET_PACKET_HEAD),
			0,
			(struct sockaddr*)&pAddr->xAddr,pAddr->nAddrLen );
	}

	return nRet;
}

int DYSvrNetMan::UdpViewerCommand(SOCKET hSocket,TG_UDP_ADDR *pAddr,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_TGD_CLIENT_ALIVE:
	case MSG_TYPE_TGD_RETRANS_PACKET:
	case MSG_TYPE_TGD_CHANGE_NET_STATE:
		{
			//nRet = m_xSessionMan.SetCommand( (NET_PACKET*)pMsgHead ); 
		}
		break;
	default:
		{
			nRet = TG_ERR_FAILURE;
			break;
		}
	}

	return nRet;
}